package com.company.phonebook;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class addMenu extends Activity {
	final Calendar c = Calendar.getInstance();
	static ProgressDialog mapLoadingDialog = null;
	private int mYear = c.get(Calendar.YEAR);
	private int mMonth = c.get(Calendar.MONTH);
	private int mDay = c.get(Calendar.DAY_OF_MONTH);
	
	static final int BIRTH_DIALOG_ID = 0;
	static final int GROUP_DIALOG_ID = 1;
	
	private EditText nameText;
	private EditText numberText;
	private EditText birthText;
	private EditText groupText;
	private EditText emailText;
	private EditText twitterText;
	private EditText blogText;
	private Button locationText;
	private Spinner emailSelectSpinner;
	
	Location currentLocation;
	LocationManager locationManager;
	double currentlatitude;
	double currentlongitude;
	
	String bestProvider;		
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_menu);						
		
		nameText		= (EditText) findViewById(R.id.name_text);
		numberText		= (EditText) findViewById(R.id.number_text);
		birthText		= (EditText) findViewById(R.id.birth_text);
		groupText		= (EditText) findViewById(R.id.group_text);
		emailText		= (EditText) findViewById(R.id.email_text);
		twitterText		= (EditText) findViewById(R.id.twitter_text);
		blogText		= (EditText) findViewById(R.id.blog_text);
		locationText	= (Button) findViewById(R.id.location_text);										
		
		emailSelectSpinner = (Spinner) findViewById(R.id.select_email_spinners);				 						
		
		ArrayAdapter<CharSequence> emailSelectSpinnerAdapter = 
			ArrayAdapter.createFromResource(this, R.array.email_elements, android.R.layout.simple_spinner_item);
		
		emailSelectSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		emailSelectSpinner.setAdapter(emailSelectSpinnerAdapter);
		
		locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);						
		bestProvider = locationManager.getBestProvider(new Criteria(), true);		
		Log.i("", bestProvider);		
		
		locationManager.requestLocationUpdates(bestProvider, 6000, 500.0f, new LocationListener() {
			
			@Override
			public void onStatusChanged(String provider, int status, Bundle extras) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onProviderEnabled(String provider) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onProviderDisabled(String provider) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onLocationChanged(Location location) {
				// TODO Auto-generated method stub
				
			}
		});
		
		ImageButton addButton = (ImageButton) findViewById(R.id.add_button);		
		addButton.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {				
				if(nameText.getText().length() == 0)
					Toast.makeText(addMenu.this, "Please Enter the NAME to add Contact", Toast.LENGTH_SHORT).show();
				else
					ProgressDialog.show(addMenu.this, "", "Adding to your Contacts",true, true);
			}
		});
		
		Button nameClearButton = (Button) findViewById(R.id.name_clear_button);
        nameClearButton.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				nameText.setText("");
			}
		});
        
        Button numberClearButton = (Button) findViewById(R.id.number_clear_button);
        numberClearButton.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				numberText.setText("");
			}
		});
        
        Button birthClearButton = (Button) findViewById(R.id.birth_clear_button);
        birthClearButton.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				birthText.setText("");
			}
		});
        
        Button groupClearButton = (Button) findViewById(R.id.group_clear_button);
        groupClearButton.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				groupText.setText("");
			}
		});
        
        Button emailClearButton = (Button) findViewById(R.id.email_clear_button);
        emailClearButton.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				emailText.setText("");
			}
		});
        
        Button twitterClearButton = (Button) findViewById(R.id.twitter_clear_button);
        twitterClearButton.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				twitterText.setText("");
			}
		});
        
        Button blogClearButton = (Button) findViewById(R.id.blog_clear_button);
        blogClearButton.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				blogText.setText("");
			}
		});
        
        Button locationClearButton = (Button) findViewById(R.id.location_clear_button);
        locationClearButton.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				locationText.setText("");
			}
		});
        
        Button birthSelectButton = (Button) findViewById(R.id.birth_select_button);
        birthSelectButton.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				showDialog(BIRTH_DIALOG_ID);
			}
		});      
        
        Button groupSelectButton = (Button) findViewById(R.id.group_select_button);
        groupSelectButton.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				showDialog(GROUP_DIALOG_ID);
			}
		});   
        
        Button blogVisitButton = (Button) findViewById(R.id.blog_visit_button);
        blogVisitButton.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				Uri uri;
				String blog = blogText.getText().toString();
				if(blog.length() != 0){				
					if(blog.contains("http://"))
						uri = Uri.parse(blogText.getText().toString());
					else
						uri = Uri.parse("http://" + blogText.getText().toString());
					
					Intent intent = new Intent(Intent.ACTION_VIEW, uri);
					startActivity(intent);
				}			
				else
					Toast.makeText(addMenu.this, "Please put URL to visit blog", Toast.LENGTH_SHORT).show();
			}
		});
        
        Button updateLocationButton = (Button) findViewById(R.id.location_update_button);
        updateLocationButton.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {				
				currentLocation = locationManager.getLastKnownLocation(bestProvider);									
				updateWithCurrentLocation(currentLocation);
				locationText.setText(currentlongitude + ", " + currentlatitude );
			}
		});
        
        locationText.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				if(locationText.getText().length() != 0){	
					mapLoadingDialog = ProgressDialog.show(addMenu.this, "", "Please wait",true,true);
					 new Thread() { 
		                    public void run() { 
		                         try{ 
		                        	Intent intent = new Intent().setClass(addMenu.this, ShowCurrentLocation.class);
		         					intent.putExtra("latitude", currentlatitude);
		         					intent.putExtra("longitude", currentlongitude);
		         					intent.putExtra("provider", bestProvider);		         					
		         					startActivity(intent); 		                               
		                         } catch (Exception e) {  } 		                          
		                    } 
		               }.start(); 					
				}
				else
					Toast.makeText(addMenu.this, "Please CLICK the Update Location Button", Toast.LENGTH_SHORT).show();
			}
		});
        
        class EmailOnItemSelectedListener implements OnItemSelectedListener{
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {	
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {				
			}        	
        }        
        emailSelectSpinner.setOnItemSelectedListener(new EmailOnItemSelectedListener());        
	}

	private void updateWithCurrentLocation(Location currentLocation) {
		if(currentLocation != null){
			currentlatitude = currentLocation.getLatitude();
			currentlongitude = currentLocation.getLongitude();
			Log.i("", "lat : " + currentlatitude );
			Log.i("", "lon : " + currentlongitude);
		}
		else
			Log.i("", "currentlocation is null");
		
	}

	private void upDateBirthText() {
		birthText.setText(new StringBuilder()
				.append(mMonth + 1).append("-")
				.append(mDay).append("-")
				.append(mYear));
	}
	
	private DatePickerDialog.OnDateSetListener mDateSetListener = 
		new OnDateSetListener() {			
			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				mYear = year;
				mMonth = monthOfYear;
				mDay = dayOfMonth;
				upDateBirthText();			
			}
		};	
		
	private android.content.DialogInterface.OnClickListener mGroupSetListener =
		new android.content.DialogInterface.OnClickListener() {				
			public void onClick(DialogInterface dialog, int which) {
				String[] group = getResources().getStringArray(R.array.Group);
				groupText.setText(group[which]);			
			}
		};
		
	@Override
	protected Dialog onCreateDialog(int id) {
	    switch (id) {
	    case BIRTH_DIALOG_ID:
	        return new DatePickerDialog(this,
	                    mDateSetListener,
	                    mYear, mMonth, mDay);
	    case GROUP_DIALOG_ID:
	    	AlertDialog.Builder dialog = new AlertDialog.Builder(this)
	    	.setTitle("Select Group")
	    	.setItems(R.array.Group, mGroupSetListener);	
	    	return dialog.create();
	    }
	    return null;
	}
}
